package com.lancoo.answer.util;

import android.text.Html;
import android.text.Layout;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.text.style.SubscriptSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.widget.span.FillAnwerSpan;
import com.lancoo.answer.widget.span.UrlImageSpan;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2021/12/2 10:05
 * Description:
 */
public class RichTextUtils {
    private static final String TAG = "RichTextUtils";
    private static final String firstEm="\t\t\t\t";




    /**
     * 参考答案富文本显示
     * @param queseAnswer 参考答案
     * @param isNeedTr 是否需要首行缩进
     * @return char
     */
    public static CharSequence getQueseAnswerStr(String queseAnswer,boolean isNeedTr,boolean isChineseAnswer) {
        Log.e("getQueseAnswerStr",isNeedTr+"->"+queseAnswer);
        Document document = Jsoup.parse(queseAnswer);
        Elements elements_p = document.select("P");
        boolean hasPTab=false;
        for (Element element : elements_p) {
            element.tagName("span");
            element.append("<br/>");
            hasPTab=true;
        }
        List<Node> nodes = document.body().childNodes();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        int index=0;
        for (Node node : nodes) {
            index++;
            if(index==1&&node instanceof Element){ //如果标题之前还有空标签的话，去除处理
                Element e= (Element) node;
                String text = e.text();
                if(TextUtils.equals("span", node.nodeName())&&
                        TextUtils.isEmpty(text)){
                    continue;
                }
            }

            String align = node.attr("align");
            SpannableString spannableString = new SpannableString(Html.fromHtml(node.outerHtml()));
            if (!TextUtils.isEmpty(align)) {
                Layout.Alignment tag;
                switch (align.toLowerCase()) {
                    case "center":
                        tag = Layout.Alignment.ALIGN_CENTER;

                        break;
                    case "right":
                        tag = Layout.Alignment.ALIGN_OPPOSITE;
                        break;
                    default:
                        tag = Layout.Alignment.ALIGN_NORMAL;

                }
                AlignmentSpan.Standard alignmentSpan = new AlignmentSpan.Standard(tag);
                spannableString.setSpan(alignmentSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                if (isNeedTr&&TextUtils.equals("span", node.nodeName())) {
                    spannableStringBuilder.append(firstEm);
                    if(isChineseAnswer){
                        spannableStringBuilder.append("");
                    }
                }
            }
            if(isNeedTr&&!hasPTab){
                spannableStringBuilder.append(firstEm);
                if(isChineseAnswer){
                    spannableStringBuilder.append("");
                }
            }
            spannableStringBuilder.append(spannableString);
        }

        return getQueseAnalysisCharSequence(spannableStringBuilder);
    }


    /**
     * 参考答案富文本显示
     * @param queseAnswer 参考答案
     * @param isNeedTr 是否需要首行缩进
     * @return char
     */
    public static CharSequence getAudioArticle(String queseAnswer,boolean isNeedTr) {

        Document document = Jsoup.parse(queseAnswer);
        Elements elements_p = document.select("P");
        boolean hasPTab=false;
        for (Element element : elements_p) {
            element.tagName("span");
            element.append("<br/>");
            hasPTab=true;
        }
        List<Node> nodes = document.body().childNodes();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        int index=0;
        for (Node node : nodes) {
            index++;
            if(index==1&&node instanceof Element){ //如果标题之前还有空标签的话，去除处理
                Element e= (Element) node;
                String text = e.text();
                if(TextUtils.equals("span", node.nodeName())&&
                        TextUtils.isEmpty(text)){
                    continue;
                }
            }

            String align = node.attr("align");
            SpannableString spannableString = new SpannableString(Html.fromHtml(node.outerHtml()));
            if (!TextUtils.isEmpty(align)) {
                Layout.Alignment tag;
                switch (align.toLowerCase()) {
                    case "center":
                        tag = Layout.Alignment.ALIGN_CENTER;
                        break;
                    case "right":
                        tag = Layout.Alignment.ALIGN_OPPOSITE;
                        break;
                    default:
                        tag = Layout.Alignment.ALIGN_NORMAL;

                }
                AlignmentSpan.Standard alignmentSpan = new AlignmentSpan.Standard(tag);
                spannableString.setSpan(alignmentSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                if (isNeedTr&&TextUtils.equals("span", node.nodeName())) {
                    spannableStringBuilder.append(firstEm);
                }
            }
            if(isNeedTr&&!hasPTab){
                spannableStringBuilder.append(firstEm);
            }
            spannableStringBuilder.append(spannableString);
        }

        return getQueseAnalysisCharSequence(spannableStringBuilder);
    }


    public static CharSequence getQueseAnalysisCharSequence(TextView tv, Spanned spanned) {
        SpannableString spannableString = new SpannableString(spanned);
        UnderlineSpan[] spans = spannableString.getSpans(0, spannableString.length(), UnderlineSpan.class);
        for (int i = 0; i < spans.length; i++) {
            UnderlineSpan span = spans[i];
            int spanStart = spannableString.getSpanStart(span);
            int spanEnd = spannableString.getSpanEnd(span);
            CharSequence charSequence = spannableString.subSequence(spanStart, spanEnd);
            String content = charSequence.toString();
            String[] split = content.split(" ");
            if (split.length > 1) {
                int addLength = 0;
                for (int j = 0; j < split.length; j++) {
                    String subAsk = split[j] + (j < split.length - 1 ? " " : "");
                    FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                    fillAnwerSpan.setDrawableLineType(3);
                    fillAnwerSpan.setUnderLine(true);
                    fillAnwerSpan.setmText(subAsk);
                    spannableString.setSpan(fillAnwerSpan, spanStart + addLength, spanStart + addLength + subAsk.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    addLength += subAsk.length();
                }
            } else {
                FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                fillAnwerSpan.setDrawableLineType(3);
                fillAnwerSpan.setUnderLine(true);
                fillAnwerSpan.setmText(charSequence.toString());
                spannableString.setSpan(fillAnwerSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }


        }

        ImageSpan[] imageSpans = spannableString.getSpans(0, spannableString.length(), ImageSpan.class);
        List<String> imgList=new ArrayList<>();
        for (int i = 0; i < imageSpans.length; i++) {
            ImageSpan imageSpan = imageSpans[i];
            int spanStart = spannableString.getSpanStart(imageSpan);
            int spanEnd = spannableString.getSpanEnd(imageSpan);
            String source = imageSpan.getSource().replace("<u>  </u>","_");
            imgList.add(source);
            final int position=i;
            UrlImageSpan urlImageSpan=new UrlImageSpan(tv.getContext(),source,tv);
            ClickableSpan clickableSpan=new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    EasyPhotos.startPreviewPaths((FragmentActivity) widget.getContext(), GlideEngine.getInstance(),(ArrayList<String>)imgList,true,position);
                }
            };
            spannableString.setSpan(clickableSpan, spanStart , spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(urlImageSpan, spanStart , spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        int endIndex = spannableString.length();
        for (int i = spannableString.length() - 1; i >= 0; i--) {
            char c = spannableString.charAt(i);
            if (!TextUtils.isEmpty(("" + c).trim())) {
                break;
            }
            endIndex = i;
        }
        SubscriptSpan[] subscriptSpans = spannableString.getSpans(0, spannableString.length(), SubscriptSpan.class);
        if(subscriptSpans!=null&&subscriptSpans.length>0){
            Log.e("eee","有公式下标"+subscriptSpans.length);
            float textSize = tv.getTextSize()*0.5f;
            for (SubscriptSpan sub:subscriptSpans){
                int spanStart = spannableString.getSpanStart(sub);
                int spanEnd = spannableString.getSpanEnd(sub);
                spannableString.setSpan(new AbsoluteSizeSpan((int)textSize),spanStart,spanEnd,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString.subSequence(0, endIndex);
    }

    public static CharSequence getQueseAnalysisCharSequence(Spanned spanned) {
        int endIndex = spanned.length();
        for (int i = spanned.length() - 1; i >= 0; i--) {
            char c = spanned.charAt(i);
            Log.e("Html", i + ":" + c);
            if (!TextUtils.isEmpty(("" + c).trim())) {
                break;
            }
            endIndex = i;
        }
        return spanned.subSequence(0, endIndex);
    }


    /**
     * 改错题答案解析数据处理
     * @param items itemList
     * @return str
     */
    public static String getCorrectAnalysis(List<Item> items) {

        StringBuilder spannableStringBuilder = new StringBuilder();
        if (items.size() == 1) {
            String itemAnalysis = items.get(0).getItemAnalysis();
            if (TextUtils.isEmpty(itemAnalysis)) {
                itemAnalysis = "...略";
            }
            spannableStringBuilder.append(itemAnalysis);
        } else {
            boolean isAllEmpty=true;
            for (int i = 0; i < items.size(); i++) {
                Item item = items.get(i);
                String itemAnalysis = item.getItemAnalysis();
                if (TextUtils.isEmpty(itemAnalysis)) {
                    itemAnalysis = "...略";
                }else{
                    isAllEmpty=false;
                }
                Document parse = Jsoup.parse(itemAnalysis);
                List<Node> newNodes = parse.body().childNodes();
                spannableStringBuilder.append(item.getSortIndex()).append(". ");
                Node lastNode = null;
                boolean isFristP = true;
                for (Node node : newNodes) {
                    if (TextUtils.equals(node.nodeName(), "p")) {
                        if (isFristP) {
                            isFristP = false;
                            if (lastNode != null) {
                                if (!TextUtils.isEmpty(lastNode.outerHtml())) {
                                    if (node instanceof Element) {
                                        Element element = (Element) node;
                                        element.prepend("<br/>");
                                    }
                                }
                            }
                        }
                        if (node instanceof Element) {
                            Element element = (Element) node;
                            element.tagName("span");
                            element.append("<br/>");
                        }
                    }
                    spannableStringBuilder.append(node.outerHtml());
                    if(newNodes.size()==1&&isFristP){
                        spannableStringBuilder.append("<br/>");
                    }
                }
            }
            if(isAllEmpty){
                spannableStringBuilder=new StringBuilder();
                spannableStringBuilder.append("...略");
            }
        }
        return spannableStringBuilder.toString();
    }






}
